//
//  OSCCaptureViewController.m
//  Tektronix
//
//  Created by Jerry.Yang on 2020/6/12.
//  Copyright © 2020 Jerry.Yang. All rights reserved.
//

#import "OSCCaptureViewController.h"

@interface OSCCaptureViewController ()

@end

@implementation OSCCaptureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    self.spanel = [self createSavePanel];
}

-(void)viewDidAppear{
    [self updateDeviceName];
}

-(void)updateDeviceName{
    if ([self.delegate respondsToSelector:@selector(getFirstInstrumentDevice)]) {
        NSString *name = [self.delegate getFirstInstrumentDevice];
        if (name==nil) {
            self.deviceName.stringValue=@"";
        }else{
            self.deviceName.stringValue=[self.delegate getFirstInstrumentDevice];
        }
    }
}

-(NSSavePanel *)createSavePanel{
    NSSavePanel *panel = [NSSavePanel savePanel];
    panel.title = @"Save Picture";
    [panel setMessage:@"Please select saved directory"];
        //    [panel setNameFieldStringValue:@"123"];
    [panel setAllowedFileTypes:@[@"png"]];
    [panel setExtensionHidden:NO];
    [panel setCanCreateDirectories:YES];
    return panel;
}

- (IBAction)researchUSBPort:(id)sender {
    if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(buildUSBPort)]){
        [self.delegate buildUSBPort];
    }
    [self updateDeviceName];
}

- (IBAction)refresh:(id)sender {
    if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(getNewScreenshotData)]){
        self.imageView.image=[[NSImage alloc]initWithData:[self.delegate getNewScreenshotData]];
    }
}

- (IBAction)save:(id)sender {
    NSData *data = [self.imageView.image TIFFRepresentation];
    if (data==nil || data.length==0) {
        [self showAlertView:@"No Image need to save!" msg:nil];
        return;
    }
    [self.spanel beginSheetModalForWindow:self.view.window completionHandler:^(NSModalResponse result){
        NSString *path = [[self.spanel URL]path];
        [data writeToFile:path atomically:YES];
    }];
}

- (IBAction)saveDefault:(id)sender{
    NSData *data = [self.imageView.image TIFFRepresentation];
    if (data==nil || data.length==0) {
        [self showAlertView:@"No Image need to save!" msg:nil];
        return;
    }
    NSString *defaultpath = [self default_picture_folder];
    if (defaultpath!=nil){
        NSString *picpath = [defaultpath stringByAppendingFormat:@"/%@.png",[self date_time_string]];
        [data writeToFile:picpath atomically:YES];
        [self showAlertView:[@" Saved !\n" stringByAppendingString:picpath] msg:@"Notify"];
    }
}

- (IBAction)openDefaultPictureFolder:(id)sender{
    NSString *defaultPath = [self default_picture_folder];
    if (defaultPath!=nil) {
        system([[@"open " stringByAppendingString:defaultPath] UTF8String]);
    }
    else{
        [self showAlertView:@"Fail to create default directory path!" msg:nil];
    }
}

-(void)showAlertView:(NSString *)information msg:(NSString *)msginfo{
    if (msginfo==nil || msginfo.length==0) msginfo=@"Error:";
    NSAlert *alert = [[NSAlert alloc] init];
    alert.messageText = msginfo;
    [alert setShowsHelp:NO];
    NSString* name = [NSString stringWithFormat:@"%@",information];
    alert.informativeText = name;
    alert.alertStyle = NSAlertStyleWarning;
    [alert addButtonWithTitle:@"Ok"];
    [alert runModal];
}

-(NSString *)date_time_string{
    // 获取代表公历的NSCalendar对象
    NSCalendar *gregorian = [[NSCalendar alloc]
     initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
     NSCalendarUnitMonth |  NSCalendarUnitDay |
     NSCalendarUnitHour |  NSCalendarUnitMinute |
     NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents* comp = [gregorian components: unitFlags
     fromDate:dt];
    return [NSString stringWithFormat:@"%ld-%ld-%ld_%ld-%ld-%ld",comp.year,comp.month,comp.day,comp.hour,comp.minute,comp.second];
}

-(NSString *)default_picture_folder{
    NSArray*documentPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *docPath = [documentPaths objectAtIndex:0];
    NSString *tekpath = [NSString stringWithFormat:@"%@/%@",docPath,@"TekPics"];
    BOOL isDir;
    BOOL ret = [[NSFileManager defaultManager] fileExistsAtPath:tekpath isDirectory:&isDir];
    if (!ret || (ret && !isDir)) {
        NSError *error;
        BOOL retmk = [[NSFileManager defaultManager] createDirectoryAtPath:tekpath withIntermediateDirectories:YES attributes:nil error:&error];
        if (retmk){
            return tekpath;
        }
        else{
            [self showAlertView:[@"Fail to create default directory path!" stringByAppendingString:error.description] msg:nil];
            return nil;
        }
    }
    return tekpath;
}

@end
